package com.example.demoapp.activity;

import static com.example.demoapp.bean.util.KeyBoardUtils.hintKeyboard;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.demoapp.R;
import com.example.demoapp.bean.Res;
import com.example.demoapp.bean.User;
import com.example.demoapp.config.URLs;
import com.example.demoapp.bean.util.JSONParser;
import com.example.demoapp.vollley.MySingleton;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {

    private Context mContext;
    //登录按钮
    private Button btn_login;
    //用户账号
    private EditText user_name;
    //用户密码
    private EditText user_password;
    //注册
    private TextView register;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //绑定当前activity
        mContext = LoginActivity.this;
        setHintKeyboardView(getWindow().getDecorView());
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle("登录");
//            bar.setDisplayHomeAsUpEnabled(true);
            bar.setHomeButtonEnabled(true);
        }
        //绑定视图
        register = findViewById(R.id.text_reg);
        btn_login = findViewById(R.id.btn_login);
        user_name = findViewById(R.id.user_name);
        user_password = findViewById(R.id.user_password);
        user_name.setText("Admin1");
        user_password.setText("1");
        //点击事件
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = user_name.getText().toString().trim();
                String password = user_password.getText().toString().trim();
                // 检查用户名和密码是否为空
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                Map map=new HashMap();
                // 输入参数
                map.put("userName", username);//Admin
                map.put("password", password);//123
                MySingleton.getInstance(mContext.getApplicationContext()).getRequestQueue().add(new JsonObjectRequest(URLs.Login, new JSONObject(map),
                        new Response.Listener() {
                            @Override
                            public void onResponse(Object response) {
                                Res res = JSONParser.parseJson(response.toString());
                                if (res.isSuccess()){
                                    Log.d("login_response",res.toString());
                                    Toast.makeText(mContext, "登录成功", Toast.LENGTH_SHORT).show();
                                    // 保存用户信息
                                    User user = JSONParser.parseUserJson(res.getData().toString());
                                    SharedPreferences preferences = getSharedPreferences("LoginPrefs", Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putString("username", username);
                                    editor.putString("password", password);
                                    editor.putString("user",new Gson().toJson(user));
                                    editor.putString("token",user.getToken());
                                    editor.apply();
                                    Intent info = new Intent();
                                    info.setClass(mContext, MainActivity.class);
                                    startActivity(info);
                                    finish();
                                }else{
                                    Toast.makeText(mContext, "登录失败，请检查用户名与密码", Toast.LENGTH_SHORT).show();
                                    // 清空密码
                                    user_name.setText("");
                                    user_password.setText("");
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, "网络出错", Toast.LENGTH_SHORT).show();
                        // 清空密码
                        user_name.setText("");
                        user_password.setText("");
                    }
                }));
            }
        });

        // 注册页面开启
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,RegisterActivity.class);
                //用一种特殊方式开启Activity，为了数据传递
                startActivityForResult(intent, 11);
            }
        });
    }


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // reg销毁时候传回数据
        super.onActivityResult(requestCode, resultCode, data);
        if (data.getStringExtra("username")!=null){
            String username = data.getStringExtra("username");
            String password = data.getStringExtra("password");
            user_name.setText(username);
            user_password.setText(password);
        }

    }    /**
     * 设置点击软键盘之外区域，软键盘消失
     *
     * @param view
     */
    public void setHintKeyboardView(View view) {
        if (!(view instanceof EditText)) {
            view.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    hintKeyboard((Activity) mContext);
                    user_name.clearFocus();
                    user_password.clearFocus();
                    return false;
                }
            });
        }
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setHintKeyboardView(innerView);
            }
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                System.exit(0);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


}